import 'package:flutter/material.dart';
import 'loading_widget.dart';


enum FeedbackType {
  success,
  error,
  warning,
  info,
}


class FeedbackResult {
  final bool success;
  final String message;
  final FeedbackType type;

  const FeedbackResult({
    required this.success,
    required this.message,
    this.type = FeedbackType.info,
  });

  
  static FeedbackResult successResult(String message) {
    return FeedbackResult(
      success: true,
      message: message,
      type: FeedbackType.success,
    );
  }

  
  static FeedbackResult errorResult(String message) {
    return FeedbackResult(
      success: false,
      message: message,
      type: FeedbackType.error,
    );
  }

  
  static FeedbackResult warningResult(String message) {
    return FeedbackResult(
      success: false,
      message: message,
      type: FeedbackType.warning,
    );
  }

  
  static FeedbackResult infoResult(String message) {
    return FeedbackResult(
      success: true,
      message: message,
      type: FeedbackType.info,
    );
  }
}



class FeedbackMessage {
  
  static void showToast({
    required BuildContext context,
    required String message,
    FeedbackType type = FeedbackType.info,
    Duration duration = const Duration(seconds: 3),
    bool showCloseButton = false,
  }) {
    final color = _getColorForType(type, context);
    final icon = _getIconForType(type);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            Icon(
              icon,
              color: color,
              size: 20,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                message,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            if (showCloseButton)
              IconButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).hideCurrentSnackBar();
                },
                icon: const Icon(Icons.close, size: 18),
              ),
          ],
        ),
        backgroundColor: Colors.grey[50],
        elevation: 6,
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.all(16),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
          side: BorderSide(color: color.withValues(alpha: 0.1)),
        ),
        duration: duration,
      ),
    );
  }

  
  static Future<void> showDialogMessage({
    required BuildContext context,
    required String title,
    required String message,
    FeedbackType type = FeedbackType.info,
    String? confirmText,
    String? cancelText,
    VoidCallback? onConfirm,
    bool showCancel = false,
    bool isDestructive = false,
  }) {
    final color = _getColorForType(type, context);
    final icon = _getIconForType(type);
    final theme = Theme.of(context);

    return showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        title: Row(
          children: [
            Icon(
              icon,
              color: color,
              size: 24,
            ),
            const SizedBox(width: 12),
            Text(
              title,
              style: theme.textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        content: Text(
          message,
          style: theme.textTheme.bodyMedium,
        ),
        actions: [
          if (showCancel && cancelText != null)
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(cancelText),
            ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              onConfirm?.call();
            },
            style: TextButton.styleFrom(
              foregroundColor: isDestructive ? theme.colorScheme.error : null,
            ),
            child: Text(confirmText ?? '确定'),
          ),
        ],
      ),
    );
  }

  
  static void showBottomSheetMessage({
    required BuildContext context,
    required String message,
    FeedbackType type = FeedbackType.info,
    Duration? autoHideDuration,
  }) {
    final color = _getColorForType(type, context);
    final icon = _getIconForType(type);

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: Row(
          children: [
            Icon(
              icon,
              color: color,
              size: 24,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                message,
                style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            IconButton(
              onPressed: () => Navigator.of(context).pop(),
              icon: const Icon(Icons.close),
            ),
          ],
        ),
      ),
    );

    if (autoHideDuration != null) {
      Future.delayed(autoHideDuration, () {
        if (Navigator.of(context).canPop()) {
          Navigator.of(context).pop();
        }
      });
    }
  }

  
  static void showPageFeedback({
    required BuildContext context,
    required String message,
    FeedbackType type = FeedbackType.info,
    String? iconPath,
  }) {
    final color = _getColorForType(type, context);
    final icon = _getIconForType(type);

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: color,
              size: 48,
            ),
            const SizedBox(height: 16),
            Text(
              message,
              style: Theme.of(context).textTheme.bodyLarge,
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  
  static Color _getColorForType(FeedbackType type, BuildContext context) {
    final theme = Theme.of(context);
    
    switch (type) {
      case FeedbackType.success:
        return Colors.green;
      case FeedbackType.error:
        return theme.colorScheme.error;
      case FeedbackType.warning:
        return Colors.orange;
      case FeedbackType.info:
        return theme.colorScheme.primary;
    }
  }

  
  static IconData _getIconForType(FeedbackType type) {
    switch (type) {
      case FeedbackType.success:
        return Icons.check_circle;
      case FeedbackType.error:
        return Icons.error;
      case FeedbackType.warning:
        return Icons.warning;
      case FeedbackType.info:
        return Icons.info;
    }
  }
}


class ConfirmationDialog {
  
  static Future<bool> show({
    required BuildContext context,
    required String title,
    required String message,
    String confirmText = '确认',
    String cancelText = '取消',
    FeedbackType messageType = FeedbackType.info,
    bool isDestructive = false,
    bool showCancel = true,
  }) async {
    
    await FeedbackMessage.showDialogMessage(
      context: context,
      title: title,
      message: message,
      type: messageType,
      confirmText: confirmText,
      cancelText: showCancel ? cancelText : null,
      showCancel: showCancel,
      isDestructive: isDestructive,
    );
    
    
    return false;
  }

  
  static Future<bool> showDeleteConfirmation({
    required BuildContext context,
    required String itemName,
    String? customMessage,
  }) async {
    return await show(
      context: context,
      title: '确认删除',
      message: customMessage ?? '确定要删除 "$itemName" 吗？此操作无法撤销。',
      confirmText: '删除',
      cancelText: '取消',
      messageType: FeedbackType.warning,
      isDestructive: true,
    );
  }

  
  static Future<bool> showExitConfirmation({
    required BuildContext context,
    bool unsavedChanges = false,
  }) async {
    return await show(
      context: context,
      title: '确认退出',
      message: unsavedChanges 
          ? '您有未保存的更改，确定要退出吗？'
          : '确定要退出应用吗？',
      confirmText: '退出',
      cancelText: '取消',
      messageType: FeedbackType.warning,
    );
  }
}



class OperationWrapper extends StatelessWidget {
  final Future<FeedbackResult> Function() operation;
  final Widget child;
  final String? loadingMessage;
  final String? successMessage;
  final String? errorMessage;
  final bool showSuccessFeedback;
  final bool showErrorFeedback;

  const OperationWrapper({
    super.key,
    required this.operation,
    required this.child,
    this.loadingMessage,
    this.successMessage,
    this.errorMessage,
    this.showSuccessFeedback = true,
    this.showErrorFeedback = true,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () async {
        try {
          LoadingDialog.show(
            context: context,
            message: loadingMessage ?? '操作中...',
          );

          final result = await operation();

          if (context.mounted) {
            LoadingDialog.hide(context);

            if (result.success) {
              if (showSuccessFeedback && successMessage != null) {
                FeedbackMessage.showToast(
                  context: context,
                  message: successMessage!,
                  type: FeedbackType.success,
                );
              }
            } else {
              if (showErrorFeedback) {
                FeedbackMessage.showToast(
                  context: context,
                  message: result.message,
                  type: FeedbackType.error,
                );
              }
            }
          }
        } catch (e) {
          if (context.mounted) {
            LoadingDialog.hide(context);
            
            FeedbackMessage.showToast(
              context: context,
              message: '操作失败：$e',
              type: FeedbackType.error,
            );
          }
        }
      },
      child: child,
    );
  }
}